package mapper

import (
	"github.com/beego/beego/v2/client/orm"
	"ksd-social-api/modules/user/model"
)

type UserMapper struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户
 */
func (service *UserMapper) SaveUser(user model.User) (dbuser *model.User) {
	// 创建orm对象
	mysql := orm.NewOrm()
	// 保存用户
	_, err := mysql.Insert(&user)
	if err == nil {
		return &user
	}
	return nil
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (service *UserMapper) GetUser(id uint64) *model.User {
	// 创建orm对象
	mysql := orm.NewOrm()
	// 保存用户
	var user model.User
	err := mysql.Raw("select * from xk_user where id = ?").SetArgs(id).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户查询用户名
 */
func (service *UserMapper) GetUserByUserName(username string) *model.User {
	// 创建orm对象
	mysql := orm.NewOrm()
	// 保存用户
	var user model.User
	err := mysql.Raw("select * from xk_user where username = ?").SetArgs(username).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc 修改密码
 */
func (mapper *UserMapper) UpdatePwd(userId uint64, uuid string, newPwd string) (flag bool, err error) {
	// 1: 获取链接
	db := orm.NewOrm()
	// 2: 开始执行修改密码的sql语句
	exec, _ := db.Raw("UPDATE xk_user SET password = ? and uuid = ?  WHERE id = ?").SetArgs(newPwd, uuid, userId).Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil

}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  更新用户信息
 */
func UpdateInfo(user *model.User) int64 {
	// 创建orm对象
	mysql := orm.NewOrm()
	ruser := model.User{ID: user.ID}
	if mysql.Read(&ruser) == nil {
		ruser.Telephone = user.Telephone
		ruser.Address = user.Address
		ruser.Sign = user.Sign
		ruser.Male = user.Male
		if num, err := mysql.Update(&ruser, "telephone", "address", "sign", "male"); err == nil {
			return num
		}
	}
	return 0
}
